package com.control;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dao.SqlOfUser;
import com.servlet.M;
import com.servlet.M2;
import com.servlet.My;
import hyl.core.MyFun;
import hyl.core.info.Content;
import hyl.core.safe.VerifyCode;
import hyl.ext.base.MySession;
import hyl.ext.base.Response;
import hyl.ext.base.SessionFactory;

/**
 * 
 * <p>
 * @className: UserSeviceMq
 * </p>
 * <p>
 * Description: 仅适用于事务方法和长时请求方法
 * </p>
 * 
 * @author: zoudyaou qq:37798955
 * @date: 2018年11月20日 上午11:26:00
 * @copyright: 2018 zoudayou Inc. All rights reserved.
 *             注意：代码版权归邹达有所有，任何人未经授权不得私自用于商业目的
 */
@Controller("loginControl")
public class SystemControl {
	// private static final long serialVersionUID = 1L;
	VerifyCode vu = new VerifyCode();

	public SystemControl() {
	}

	///// 验证码验证码验证码验证码////
	// 生成图片验证码
	// 请求刷新验证码
	@RequestMapping("/ex/getVerifyCode")
	public void getVerifyCode(HttpServletRequest req, HttpServletResponse response,
			@RequestParam Map<String, String> R) {
		OutputStream os;
		try {
			os = response.getOutputStream();
			String code = vu.outputVerifyImage(150, 40, os, 4);
			// tk.setICode(code);
			MySession tk = My.getSession(req);
			tk.icode = code;
			// System.out.println(code);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping("/ex/start")
	public void start(HttpServletRequest req, HttpServletResponse res, @RequestParam Map<String, String> R)
			throws ServletException, IOException {
		MySession tk = SessionFactory.getSession(req, res);
		tk.start();
	}

	// 登录 一进来就默认 计数器+1,如果正确就重置状态 start,或强制性阻拦 stop
	@RequestMapping("/l/login")
	@ResponseBody
	public String login(HttpServletRequest req, HttpServletResponse res, @RequestParam Map<String, String> R)
			throws ServletException, IOException {
		Content ct = flogin(req, res, R);
		return ct.toJsonString();
	}

	public Content flogin(HttpServletRequest req, HttpServletResponse res, Map<String, String> R)
			throws ServletException, IOException {

		MySession tk = My.getSession(req);
		String checkcode = R.get("imgcode");
		String tk_code = tk.icode;
		String name = R.get("name");
		String pass = R.get("pass");

		/*
		 * StringBuffer url = req.getRequestURL(); boolean flag = Hand.url_比对(appid,
		 * url.toString()); if(!flag) { tk.msg.setCode(0, "域名访问限制"); return tk.msg; }
		 * //错误的域名访问
		 */

		// String orgid = R.get("orgid");
		// 允许多次登录
		// 如果连续登陆多次,阻拦登陆
		if (tk.getUserId() == null) {// 没有token表示无权限 ,返回登录页面
			if (MyFun.isEmpty(checkcode) || MyFun.isEmpty(tk_code)
					|| !checkcode.toLowerCase().equals(tk_code.toLowerCase())) {
				tk.msg.setCode(0, M.MSG_验证码错误);
				return tk.msg;
			}
			return checkLogin(tk, name, pass);
		} else { // 会话存在
			tk.msg.setCode(1, M.MSG_登录成功);
			tk.start();
			return tk.msg;
		}
	}
	public static Content checkLogin(MySession tk, String name, String pass) {
		if (MyFun.isEmpty(name) || MyFun.isEmpty(pass)) {
			tk.msg.setCode(0, M.MSG_登录名或密码错误);
			return tk.msg;
		}
		Map<String, Object> user = SqlOfUser.login(name, pass);
		if (user.isEmpty()) {// 用户名密码错误
			tk.msg.setCode(0, M.MSG_登录名或密码错误);
			return tk.msg;
		} else {// 验证通过，完善token
			SqlOfUser.instance().setLoginSession(tk, user);
			return tk.msg;
		}
	}



	// 不经过拦截器,检查是否可以ping通
	@RequestMapping("/ex/ping")
	@ResponseBody
	public Integer ping(HttpServletRequest request, HttpServletResponse response) {
		return 1;
	}

	// 注销
	@RequestMapping("/ex/quit")
	public String quit(HttpServletRequest req, HttpServletResponse res, @RequestParam Map<String, String> R) {
		MySession tk = My.getSession(req);
		tk.reset();
		MyFun.printJson(tk);
		SessionFactory.delSession(req, tk);
		Response.clearCookie(req, res);
	
		HttpSession sess = req.getSession();
		sess.invalidate();

		return M.URL_login; // 相对于jsp
	}

	@RequestMapping("/ex/quit2")
	public String quit2(HttpServletRequest req, HttpServletResponse res, @RequestParam Map<String, String> R) {
		MySession tk = My.getSession(req);
		tk.reset();
		SessionFactory.delSession(req, tk);
		Response.clearCookie(req, res);
		HttpSession sess = req.getSession();
		sess.invalidate();
		
		return M.URL_fwlogin; // 相对于jsp
	}

	// 测试传入与传出参数
	@RequestMapping("/f/test")
	public void test(HttpServletRequest request, HttpServletResponse response) throws IOException {

		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = response.getWriter();
		Map<String, String> mm = new HashMap<String, String>();
		mm.put("cc", "val");
		out.write(JSON.toJSONString(mm));
		out.flush();
		out.close();
	}

	public String getPath(JSONObject jo, String i) {
		String id = (String) jo.get("id");
		if (id.equals(i))
			return jo.getString("path");
		else
			return null;
	}

}
